<template>
  <div>
      <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>订单管理</el-breadcrumb-item>
          <el-breadcrumb-item>订单列表</el-breadcrumb-item>
      </el-breadcrumb> -->
      <qwerty title1="首页" title2="订单管理" title3="订单列表"></qwerty>
      <el-card style="margin-top:20px">
            <el-row :gutter="20">
            <el-col :span="8">
                <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @clear="getUsers">
                <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button></el-input>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="add">添加用户</el-button>
            </el-col>
            <!-- <el-col style="text-align: right;" :span="12">
                <el-link type="primary" @click="isShow=!isShow">{{isShow?'菜单视图':'列表视图'}}</el-link>
            </el-col> -->
            </el-row>

            <el-table :data="userlist" border stript>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch
                         v-model="scope.row.mg_state"
                         @change="userStateChanged(scope.row)"
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope">
                        <el-button
                         type="primary"
                         icon="el-icon-edit"
                         size="mini"
                         @click="handleEdit(scope.row)">
                        </el-button>
                        <el-button
                         type="danger"
                         icon="el-icon-delete"
                         size="mini"
                         @click="handleDelete(scope.row)">
                        </el-button>
                        <el-tooltip
                         effect="dark"
                         content="分配角色"
                         placement="top"
                         :enterable="false"
                         >
                          <el-button
                          type="warning"
                          icon="el-icon-setting"
                          size="mini"
                          @click="setRole(scope.row)">
                          </el-button>
                        </el-tooltip>  
                    </template>
                </el-table-column>
            </el-table>
              <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
                  <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px" class="demo-addForm">
                    <el-form-item label="用户名" prop="username">
                      <el-input :disabled="!isShow" v-model="addForm.username"></el-input>
                    </el-form-item>
                    <el-form-item v-if="isShow" label="密码" prop="password">
                      <el-input v-model="addForm.password"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="addForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" prop="mobile">
                        <el-input v-model="addForm.mobile"></el-input>
                    </el-form-item>
                  </el-form>
                  <span slot="footer" class="dialog-footer">
                      <el-button @click="handleClose">取 消</el-button>
                      <el-button type="primary" @click="addUser('addForm')">确 定</el-button>
                  </span>
            </el-dialog>
            <el-pagination 
            style="text-align: center;" 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange" 
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5,10]" 
            :page-size="queryInfo.pagesize" 
            layout="total,sizes, prev, pager, next,jumper" 
            :total="total">
            </el-pagination>
      </el-card>    
  </div>
</template>

<script>
import {getUserList,stateChanged,addUsers,deleteUsers,getUsersId} from '@/api/User.js'
export default {
    name: 'users',
    created(){
    },
    components:{},
    data(){
        var checkEmail = (rule,value,cb) =>{
            const regEmail =  /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/;
            if (regEmail.test(value)){
                return cb();
            }
            cb(new Error("请输入合法的邮箱"));
        };
        var checkMobile = (rule,value,cb) =>{
            const regMonile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
             if (regMonile.test(value)){
                return cb();
            }
            cb(new Error("请输入合法的手机号"));
        }
        return{
            rules:{
                username: [{
                required: true,
                message: '请输入用户名',
                trigger: 'blur'
            }],
            email: [{
                required: true,
                message: '请输入邮箱',
                trigger: 'blur'
            },{
                validator:checkEmail,
                trigger: 'blur'
            }],
            mobile: [{
                required: true,
                message: '请输入联系方式',
                trigger: 'blur'
            },{
                validator:checkMobile,
                trigger: 'blur'
            }],
            password: [{
                required: true,
                message: '请输入密码',
                trigger: 'blur'
            }]
        },
            setRoleDialogVisible:false,
            selectedRoleId:"",
            userInfo:{},
            title:'',
            isShow:true,  
            queryInfo:{
                query:"",
                pagenum:1,
                pagesize:2,
            },
            userlist:[],
            roleList:[],
            addDialogVisible:false,
            total:0,
            dialogVisible: false,
            dialogVisible2: false,
            addForm:{
                username:"",
                password:"",
                email:"",
                mobile:"",
            },
            editDialogVisible:false,
            editForm:{},
        };
    },
    created(){
        this.getUsers();
    },
    methods:{
        add(){
            this.isShow=true;
            this.dialogVisible=true;
            this.title='添加'
        },
        async addUser(addForm) {
            this.$refs[addForm].validate(async (valid) => {
                if (valid) {
                    var msg='';
                    if(this.addForm.id!=''){
                    var {data:res}=await addUsers(`users/${this.addForm.id}`,'put',{
                        email:this.addForm.email,
                        mobile:this.addForm.mobile
                    })
                    msg='修改'
                    }else{
                    var {data:res}=await addUsers("users",'post',this.addForm)
                    msg='添加'
                    }
                    if(res.meta.status==201){
                            this.$message({
                            message: msg+'成功',
                            type: 'success'
                            });
                            this.dialogVisible = false;
                            this.getUsers();
                            this.handleClose();
                        }else if(res.meta.status==200){
                            this.$message({
                            message: msg+'成功',
                            type: 'success'
                            });
                            this.dialogVisible = false;
                            this.getUsers();
                            this.handleClose();
                        }else{
                            this.$message({
                            message: msg+'失败',
                            type: 'error'
                            });
                        }
                    
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // userForm(addFormRef){
        //     this.$refs[addFormRef].resetFields();
        //     this.addForm.username = '';
        //     this.addForm.password = '';
        //     this.addForm.email = '';
        //     this.addForm.mobile = '';
        //     this.dialogVisible = false;
        // },
        handleClose() {
            this.addForm.id ='';
            this.addForm.username = '';
            this.addForm.password = '';
            this.addForm.email = ''
            this.addForm.mobile = ''
            this.dialogVisible = false;
        },
        async handleEdit(row){
            this.isShow=false;
            this.dialogVisible = true;
            var {data:res} = await getUsersId('users/'+row.id);
            this.addForm.id = res.data.id;
            this.addForm.username = res.data.username;
            this.addForm.email = res.data.email;
            this.addForm.mobile = res.data.mobile;
            this.title='修改'
        },
        async handleDelete(row){
            this.$confirm('确认删除？')
            .then(async _ => {
                var {data:res} = await deleteUsers(`users/${row.id}`);
                console.log(res)
                    if(res.meta.status==200){
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    this.getUsers();
                    }else{
                    this.$message({
                        message: '删除失败',
                        type: 'error'
                    });
                    this.getUsers();
                    }
            })
            .catch(_ => {});
        },
        async userStateChanged(userinfo){
            const {data:res} = await stateChanged("users/"+userinfo.id+"/state/"+userinfo.mg_state);
            if(res.meta.status !== 200){
                userinfo.mg_state = !userinfo.mg_state;
                return this.$message.error("更新用户状态失败!");
            }
            this.$message.success("更新用户状态成功!");
        },
        handleSizeChange(newSize){
            this.queryInfo.pagenum = 1;
            this.queryInfo.pagesize = newSize;
            this.getUsers();
        },
        handleCurrentChange(pageNum){
            this.queryInfo.pagenum = pageNum;
            this.getUsers();
        },
        
        async getUsers(){
            var {data:res} = await getUserList(this.queryInfo);
            if(res.meta.status !== 200){
                return this.$message.error("获取用户列表失败!");
            }
            this.userlist = res.data.users;
            this.total = res.data.total;
        },
        
    }
}
</script>

<style>

</style>